package database;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import noyau.Question;

/**
 * @author Pasukaru
 * Class Database
 * Manages the mysql database using SQL queries
 */
public class Database {
	// Gets connection object to the mysql database
	private MysqlConnect mysql = new MysqlConnect();
	private Connection conn = mysql.connect();
	
	/**
	 * Default Constructor
	 */
	public Database (){}
	
	/**
	 * getRandomQuestion method
	 * Gets a random question in the database
	 * @return Question q
	 */
	public Question getRandomQuestion(){
		// Creates instance of Question
		Question q = null;
		try{
			Statement st = conn.createStatement();
			// Executes the SQL query to get all the question in database, order them randomly
			ResultSet rs = st.executeQuery("SELECT * FROM Questions ORDER BY RAND() LIMIT 1 ;");
			while(rs.next()){
				// Creates the Question object as the first question in the ResultSet
				q = new Question(rs.getString("Libelle"), rs.getString("ReponseA"), rs.getString("ReponseB"), rs.getString("ReponseC"), rs.getString("ReponseD"), rs.getInt("BonneRep"));
			}
		}
		catch (SQLException s){
			System.out.println("SQL statement is not executed!");
		  }
		// Returns the question
		return q;
	}
	

}
